#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2018/10/31
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :Ent_extention.py
# @Software  :PyCharm

'''eof
name:申请企业未结清信贷业务校验
code:Ent_extention
tableName:
columnName:
groups:企业征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

"""
1. select count * as factor1 from 未结清正常类贷款 where 展期 = “有”； 
2. select count * as factor2 from 未结清关注类贷款 where 展期 = “有”； 
3. select count * as factor3 from 未结清不良类贷款 where 展期 = “有”；
4. select count * as factor5 from 未结清贸易融资 where 展期 = “有”； 
5. select count * as factor6 from 未结清保理 where 垫款 = “有”；
6. select count * as factor7 from 未结清银行承兑汇票 where 垫款 = “有”； 
7. select count * as factor8 from 未结清信用证 where 垫款 = “有”； 
8. select count * as factor9 from 未结清保函 where 垫款 = “有”；
9. Factor = 加总factor1至factor8

"""


import json
import sys


# reload(sys)
# sys.setdefaultencoding('utf-8')

# 自测
# with open('data.json', 'r') as ECR_load:
#     EC = json.loads(ECR_load)['EC']




def FormatData(tableName):
    """
    数据解析
    :param tableName: 目标字段
    :return: 返回的类型为[{}]
    """

    try:
        # ecr是最外面一层表里面的
        ecr = json.loads(EC[0]["ecr"])[tableName]

        return ecr if isinstance(ecr, list) and len(ecr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    """
    数据格式转换
    :param dataValue: 数据
    :param dataType: 类型
    :return: 
    """

    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    elif dataType == 'str':
        try:
            returnData = dataValue if len(dataValue) >= 0 else None
        except:
            returnData = None

    return returnData



def Ent_extention():
    """
    申请企业未结清贷款展期次数
    :return: 
    """

    try:
        # 未结清正常类贷款 信息汇总
        ECRUnpaidNormalLoanInfo = FormatData("ECRUnpaidNormalLoanInfo")
        # 未结清关注类贷款 信息汇总
        ECRUnpaidSMLoanInfo = FormatData("ECRUnpaidSMLoanInfo")
        # 未结清不良类贷款 信息汇总
        ECRUnpaidBadLoanInfo = FormatData("ECRUnpaidBadLoanInfo")
        # 未结清贸易融资 信息汇总
        ECRTradeFinancingInfo = FormatData("ECRTradeFinancing")

        # 保理 信息汇总
        ECRFactoring = FormatData("ECRFactoring")           # 测试案例有问题
        # 银行承兑汇票 信息汇总
        ECRBankAcceptance = FormatData("ECRBankAcceptance")
        # 信用证 信息汇总
        ECRLetterCredit = FormatData("ECRLetterCredit")
        # 保函 信息汇总
        ECRLetterGuarantee = FormatData("ECRLetterGuarantee")

        if ECRUnpaidNormalLoanInfo == [{}] and ECRUnpaidSMLoanInfo == [{}] and ECRUnpaidBadLoanInfo == [{}] and \
                        ECRTradeFinancingInfo == [{}] and ECRFactoring == [{}] and ECRFactoring == [{}] and \
                        ECRBankAcceptance == [{}] and ECRLetterCredit == [{}] and ECRLetterGuarantee == [{}]:
            return u'缺失值'
        else:
            # 未结清正常类贷款
            ECRUnpaidNormalLoanCountList = []
            for i in range(len(ECRUnpaidNormalLoanInfo)):
                ECRUnpaidNormalFiveclasscode = ConvertDataType(ECRUnpaidNormalLoanInfo[i].get("Fiveclasscode"), 'str')
                ECRUnpaidNormalPaidType = ConvertDataType(ECRUnpaidNormalLoanInfo[i].get("PaidType"), 'str')
                ECRUnpaidNormalExtension = ConvertDataType(ECRUnpaidNormalLoanInfo[i].get("Extension"), 'str')

                if ECRUnpaidNormalFiveclasscode is None and ECRUnpaidNormalPaidType is None and ECRUnpaidNormalExtension is None:
                    return u'缺失值'
                else:
                    if ECRUnpaidNormalPaidType == u'未结清' and ECRUnpaidNormalFiveclasscode == u'正常' and ECRUnpaidNormalExtension == u'有':
                        ECRUnpaidNormalCount = 1
                    else:
                        ECRUnpaidNormalCount = 0

                    ECRUnpaidNormalLoanCountList.append(ECRUnpaidNormalCount)

            # 未结清关注类贷款
            ECRUnpaidSMLoanCountList = []
            for i in range(len(ECRUnpaidSMLoanInfo)):
                ECRUnpaidSMLoanFiveclasscode = ConvertDataType(ECRUnpaidSMLoanInfo[i].get("Fiveclasscode"), 'str')
                ECRUnpaidSMLoanPaidType = ConvertDataType(ECRUnpaidSMLoanInfo[i].get("PaidType"), 'str')
                ECRUnpaidSMLoanExtension = ConvertDataType(ECRUnpaidSMLoanInfo[i].get("Extension"), 'str')

                if ECRUnpaidSMLoanFiveclasscode is None and ECRUnpaidSMLoanPaidType is None and ECRUnpaidSMLoanExtension is None:
                    return u'缺失值'
                else:
                    if ECRUnpaidSMLoanPaidType == u'未结清' and ECRUnpaidSMLoanExtension == u'有' and ECRUnpaidSMLoanFiveclasscode == u'关注':
                        ECRUnpaidSMLoanCount = 1
                    else:
                        ECRUnpaidSMLoanCount = 0

                    ECRUnpaidSMLoanCountList.append(ECRUnpaidSMLoanCount)

            # 未结清不良类贷款
            ECRUnpaidBadLoanCountList = []
            for i in range(len(ECRUnpaidBadLoanInfo)):
                ECRUnpaidBadLoanExtension = ConvertDataType(ECRUnpaidBadLoanInfo[i].get("Extension"), 'str')
                ECRUnpaidBadLoanFiveclasscode = ConvertDataType(ECRUnpaidBadLoanInfo[i].get("Fiveclasscode"), 'str')
                ECRUnpaidBadLoanPaidType = ConvertDataType(ECRUnpaidBadLoanInfo[i].get("PaidType"), 'str')

                if ECRUnpaidBadLoanExtension is None and ECRUnpaidBadLoanFiveclasscode is None and ECRUnpaidBadLoanPaidType is None:
                    return u'缺失值'
                else:
                    if ECRUnpaidBadLoanExtension == u'有' and (ECRUnpaidBadLoanFiveclasscode == u'损失'
                                                              or ECRUnpaidBadLoanFiveclasscode == u'次级' or
                                                                      ECRUnpaidBadLoanFiveclasscode == u'可疑') \
                            and ECRUnpaidBadLoanPaidType == u'未结清':
                        ECRUnpaidBadLoanCount = 1
                    else:
                        ECRUnpaidBadLoanCount = 0

                    ECRUnpaidBadLoanCountList.append(ECRUnpaidBadLoanCount)

            # 未结清贸易融资
            ECRTradeFinancingUnCountList = []
            for i in range(len(ECRTradeFinancingInfo)):
                CRTradeFinancingPaidType = ConvertDataType(ECRTradeFinancingInfo[i].get("PaidType"), 'str')
                CRTradeFinancingExtension = ConvertDataType(ECRTradeFinancingInfo[i].get("Extension"), 'str')

                if CRTradeFinancingPaidType is None and CRTradeFinancingExtension is None:
                    return u'缺失值'
                else:
                    if CRTradeFinancingPaidType == u'未结清' and CRTradeFinancingExtension == u'有':
                        ECRTradeFinancingUnCount = 1
                    else:
                        ECRTradeFinancingUnCount = 0
                    ECRTradeFinancingUnCountList.append(ECRTradeFinancingUnCount)

            # 未结清保理
            ECRFactoringCountList = []
            for i in range(len(ECRFactoring)):
                ECRFactoringPaidtype = ConvertDataType(ECRFactoring[i].get("Paidtype"), 'str')
                ECRFactoringPaidbackflag = ConvertDataType(ECRFactoring[i].get("Paidbackflag"), 'str')

                if ECRFactoringPaidtype is None and ECRFactoringPaidbackflag is None:
                    return u'缺失值'
                else:
                    if ECRFactoringPaidtype == u'未结清' and ECRFactoringPaidbackflag == u'有':
                        ECRFactoringCount = 1
                    else:
                        ECRFactoringCount = 0

                    ECRFactoringCountList.append(ECRFactoringCount)


            # 未结清银行承兑汇票
            ECRBankAcceptanceCountList = []
            for i in range(len(ECRBankAcceptance)):
                ECRBankAcceptancePaidtype = ConvertDataType(ECRBankAcceptance[i].get("Paidtype"), 'str')
                ECRBankAcceptancePaidbackflag = ConvertDataType(ECRBankAcceptance[i].get("Paidbackflag"), 'str')

                if ECRBankAcceptancePaidtype is None and ECRBankAcceptancePaidbackflag is None:
                    return u'缺失值'
                else:
                    if ECRBankAcceptancePaidtype == u'未结清' and ECRBankAcceptancePaidbackflag == u'有':
                        ECRBankAcceptanceCount = 1
                    else:
                        ECRBankAcceptanceCount = 0

                    ECRBankAcceptanceCountList.append(ECRBankAcceptanceCount)

            # 未结清信用证
            ECRLetterCreditCountList = []
            for i in range(len(ECRLetterCredit)):
                ECRLetterCreditPaidtype = ConvertDataType(ECRLetterCredit[i].get("Paidtype"), 'str')
                ECRLetterCreditPaidbackflag = ConvertDataType(ECRLetterCredit[i].get("Paidbackflag"), 'str')

                if ECRLetterCreditPaidtype is None and ECRLetterCreditPaidbackflag is None:
                    return u'缺失值'

                else:
                    if ECRLetterCreditPaidtype == u'未结清' and ECRLetterCreditPaidbackflag == u'有':
                        ECRLetterCreditCount = 1
                    else:
                        ECRLetterCreditCount = 0

                    ECRLetterCreditCountList.append(ECRLetterCreditCount)

            # 未结保函
            ECRLetterGuaranteeCountList = []
            for i in range(len(ECRLetterGuarantee)):
                ECRLetterGuaranteePaidtype = ConvertDataType(ECRLetterGuarantee[i].get("Paidtype"), 'str')
                ECRLetterGuaranteePaidbackflag = ConvertDataType(ECRLetterGuarantee[i].get("Paidbackflag"), 'str')

                if ECRLetterGuaranteePaidtype is None and ECRLetterGuaranteePaidbackflag is None:
                    return u'缺失值'
                else:
                    if ECRLetterGuaranteePaidtype == u'未结清' and ECRLetterGuaranteePaidbackflag == u'有':
                        ECRLetterGuaranteeCount = 1
                    else:
                        ECRLetterGuaranteeCount = 0

                    ECRLetterGuaranteeCountList.append(ECRLetterGuaranteeCount)

            Factor = ECRUnpaidNormalLoanCountList + ECRUnpaidSMLoanCountList + ECRUnpaidBadLoanCountList + \
                     ECRTradeFinancingUnCountList + ECRFactoringCountList + ECRBankAcceptanceCountList + \
                     ECRLetterCreditCountList + ECRLetterGuaranteeCountList


            return sum(Factor)
    except:
        # 异常提示或者异常出口
        return None


result = Ent_extention()



